<?php
require_once 'Zend/Controller/Plugin/Abstract.php';

class MyPluginAuth extends Zend_Controller_Plugin_Abstract
{
	private $_auth;
	private $_acl;

	private $_noauth = array('module' => 'default',
	'controller' => 'index',
	'action' => 'loginform');

	private $_noacl = array('module' => 'default',
	'controller' => 'error',
	'action' => 'privileges');
	 
	public function __construct(Zend_Auth $auth, MyAcl $acl)
	{
		$this->_auth = $auth;
		$this->_acl = $acl;
	}

	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
		//print 'myplugin auth predispatch';
		if ($this->_auth->hasIdentity()) {
			//$role = $this->_auth->getIdentity()->role;
			$identity = $this->_auth->getIdentity(); 
			$role = $identity->role;
		} else {
			$role = 'guest';
		}

		//$this->getResponse()->append('role=', $role);
		$controller = $request->controller;
		$action = $request->action;
		$module = $request->module;
		$resource = $controller;
		//echo '<br/>param=', $module.' ::: '.$controller.' ::: '.$action.' ::: '.$resource;
		//$this->getResponse()->append('param=', 'param='.$module.' ::: '.$controller.' ::: '.$action.' ::: '.$resource); 
		if (!$this->_acl->has($resource)) {
			$resource = null;
			//$this->getResponse()->append('resurce is null','is null');
		}

		//if (!$this->_acl->isAllowed($role, $module, $controller)) {
		if (!$this->_acl->isAllowed($role, $module)) {
			//$this->getResponse()->append(' resurce','is not allowed');
			
			$request->setModuleName($this->_noauth['module']);
			$request->setControllerName($this->_noauth['controller']);
			$request->setActionName($this->_noauth['action']);
		}
	}
}